import { Navigate, useLocation, useMatches } from 'react-router-dom';
import { useAuth } from '@/context/AuthContext';
import { findMetaByPath } from '@/routes';
import { UserApi } from '@/api/user'
import { useUserStore } from '@/store/user'
// import type { AppRouteObject } from "./types";

const AuthGuard = ({ children }: { children?: React.ReactNode }) => {
  const { token } = useAuth();
  const location = useLocation();
  const meta = findMetaByPath(location.pathname)
  console.log(!token && meta?.requiresAuth)
  const { setUser } = useUserStore()

  if (!token) {
    return <Navigate to="/login" state={{ from: location }} replace />;
  }

  // UserApi.getProfile().then(res => {
  //   setUser({
  //     id: res.user.userId,
  //     username: res.user.username,
  //     email: res.user.email,
  //   })
  // })

  return <>{children}</>;
};

export default AuthGuard;